﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using VINETLIFE.BL;
using VINETLIFE.DO;
using VINETLIFE.BaseClass;

namespace VINETLIFE.AdminCP
{
    public partial class Order : System.Web.UI.Page
    {
        cmsOrdersDO objOrder = new cmsOrdersDO();
        cmsOrdersBL orderBL = new cmsOrdersBL();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request.QueryString["OrderId"]))
            {
                int orderId = int.Parse(Request.QueryString["OrderId"]);
                objOrder.Id = orderId;

                if (!IsPostBack)
                {
                    LoadData();
                    ddlOrderStatusDataSource();
                    grvOrderDetailDataSource(orderId);
                    grvOrderHistoryDataSource(orderId);
                }
            }
            else
            {
                Functions.Alert("Bạn không thể truy cập được vào trang này", "/Admincp/ListOrders.aspx");
            }
        }

        protected void grvOrderDetailDataSource(int orderId)
        {
            grvOrderDetail.DataSource = new cmsOrderDetailsBL().GetByOrderId(orderId);
            grvOrderDetail.DataBind();
        }
        protected void LoadData()
        {
            objOrder = orderBL.Select(objOrder);
            if (objOrder != null)
            {
                if (objOrder.Id > 0)
                {
                    try
                    {
                        cmsCustomerDO objCustomer = new cmsCustomerBL().Select(new cmsCustomerDO() { Id = objOrder.CustomerId });
                        txtCustomerName.Text = objCustomer.FullName;
                        txtInvoiceNumber.Text = objOrder.InvoiceNumber;
                        txtPurchaseDate.Text = objOrder.CreateDate.ToString("dd/MM/yyyy HH:mm tt");
                        txtPaymentMethod.Text = new cmsPaymentMethodBL().SelectByPaymentCode(objOrder.PaymentMethod).PaymentText;
                        txtGrandTotal.Text = objOrder.GrandTotal.ToString("#,##");
                        txtRequired.Text = objOrder.DateOfStart.ToString("dd/MM/yyyy HH:mm tt");
                        ddlOrderStatus.SelectedValue = objOrder.TransactionOrderStatus;
                        chkIsUseVinetlife.Checked = objOrder.IsUseVirtualAccount;
                        rptAccountReceivedMoney.DataSource = new cmsCustomerBL().GetReceivedMoneyUserInfo(objOrder.InvoiceNumber);
                        rptAccountReceivedMoney.DataBind();
                        if (objOrder.IsUseVirtualAccount)
                        {
                            trPayedByVinetlife.Visible = true;
                            txtPayedByVinetlifeAccount.Text = objOrder.MoneyPayedByVirtualAccount.ToString("#,##");
                        }
                        if (objOrder.PaymentMethod.Equals(EnumPaymentMethod.V_Momo) || objOrder.PaymentMethod.Equals(EnumPaymentMethod.V_MbPlus))
                        {
                            trTransactionId.Visible = true;
                            txtPaypalTransactionId.Text = objOrder.TransactionId;
                        }
                        if (objOrder.SystemStatus.Equals(EnumStatus.V_ORDER_HIDDEN))
                        {
                            btnHidden.Visible = false;
                            btnComplete.Visible = false;
                            DisableButton(btnUpdate, objOrder.InvoiceNumber);
                            btnCancelOrder.Visible = false;
                        }
                        else if (objOrder.SystemStatus.Equals(EnumStatus.V_ORDER_DELETE))
                        {
                            btnHidden.Visible = false;
                            btnDelete.Visible = false;
                            btnComplete.Visible = false;
                            DisableButton(btnUpdate, objOrder.InvoiceNumber);
                            btnCancelOrder.Visible = false;
                        }
                        if (objOrder.TransactionOrderStatus.Equals(EnumTransactionOrderStatus.V_ORDER_CANCEL))
                        {
                            btnComplete.Visible = false;
                            btnHidden.Visible = false;
                            DisableButton(btnUpdate, objOrder.InvoiceNumber);
                            btnCancelOrder.Visible = false;
                        }
                        else if (objOrder.TransactionOrderStatus.Equals(EnumTransactionOrderStatus.V_ORDER_COMPLETED))
                        {
                            btnComplete.Visible = false;
                            DisableButton(btnUpdate, objOrder.InvoiceNumber);
                            btnCancelOrder.Visible = false;
                        }
                    }
                    catch { }
                }
            }
        }
        public void DisableButton(Button btn, string invoiceNumber)
        {
            btn.Enabled = false;
            btn.Attributes.Add("onclick", Alert(invoiceNumber));
            btn.CssClass = "disable-button button-gg-green";

        }
        public string Alert(string invoiceNumber)
        {
            return "alert('Không thể thực hiện chức năng này cho đơn hàng: " + invoiceNumber + "')";
        }
        protected void grvOrderHistoryDataSource(int orderId)
        {
            grvOrderHistory.DataSource = new CS_OrderHistoryBL().GetByOrder(orderId);
            grvOrderHistory.DataBind();
        }
        protected void ddlOrderStatusDataSource()
        {
            ddlOrderStatus.DataSource = new cmsTransactionStatusBL().SelectAll();
            ddlOrderStatus.DataBind();
        }
        protected void grvOrderDetail_RowDataBound(object sender, GridViewRowEventArgs e)
        {

        }

        protected void btnComplete_Click(object sender, EventArgs e)
        {
            int userId = 0;
            try
            {
                userId = int.Parse(Session["UserID"].ToString());
                objOrder = orderBL.Select(objOrder);
                objOrder.TransactionOrderStatus = EnumTransactionOrderStatus.V_ORDER_COMPLETED;
                objOrder.LastModifiedId = userId;
                objOrder.LastSaveDate = DateTime.Now;
                objOrder.DateOfFisnish = DateTime.Now;

                orderBL.Update(objOrder);

                CS_OrderHistoryDO objOrderHistory = new CS_OrderHistoryDO();
                objOrderHistory.Action = EnumOrderHistory.V_CHANGE_COMPLETE;
                objOrderHistory.Contents = EnumOrderHistory.V_CHANGE_COMPLETE_TEXT;
                objOrderHistory.CreateDate = DateTime.Now;
                objOrderHistory.OrderId = objOrder.Id;
                objOrderHistory.UserId = userId;
                objOrderHistory.Note = txtOrderHistoryNote.Text.Trim();
                objOrderHistory.IP = Request.ServerVariables["REMOTE_ADDR"].Trim();

                new CS_OrderHistoryBL().Insert(objOrderHistory);

                //if (objOrder.IsUseVirtualAccount)
                //{
                cmsAccountReceiveMoneyBL accountReceivedMoneyBL = new cmsAccountReceiveMoneyBL();
                cmsAccountReceiveMoneyDO objAccountReceivedMoney = accountReceivedMoneyBL.SelectByOrder(objOrder.InvoiceNumber);
                if (objAccountReceivedMoney != null)
                {
                    if (objAccountReceivedMoney.ID > 0)
                    {
                        objAccountReceivedMoney.Status = EnumReceivedMoneyStatus.V_RECEIVED_OK;
                        objAccountReceivedMoney.UserId = userId;
                        accountReceivedMoneyBL.Update(objAccountReceivedMoney);
                    }
                }
                //  }
                Functions.Alert("Cập nhật thành công!", "/Admincp/ListOrders.aspx");
            }
            catch { }
        }

        protected void btnHidden_Click(object sender, EventArgs e)
        {
            int userId = 0;
            try
            {
                userId = int.Parse(Session["UserID"].ToString());
                objOrder = orderBL.Select(objOrder);
                objOrder.SystemStatus = EnumStatus.V_ORDER_HIDDEN;
                objOrder.TransactionOrderStatus = EnumTransactionOrderStatus.V_ORDER_COMPLETED;
                objOrder.LastModifiedId = userId;
                objOrder.LastSaveDate = DateTime.Now;

                orderBL.Update(objOrder);

                CS_OrderHistoryDO objOrderHistory = new CS_OrderHistoryDO();
                objOrderHistory.Action = EnumOrderHistory.V_CHANGE_HIDDEN;
                objOrderHistory.Contents = EnumOrderHistory.V_CHANGE_HIDDEN_TEXT; ;
                objOrderHistory.CreateDate = DateTime.Now;
                objOrderHistory.OrderId = objOrder.Id;
                objOrderHistory.UserId = userId;
                objOrderHistory.Note = txtOrderHistoryNote.Text.Trim();
                objOrderHistory.IP = Request.ServerVariables["REMOTE_ADDR"].Trim();

                new CS_OrderHistoryBL().Insert(objOrderHistory);

                Functions.Alert("Cập nhật thành công!", "/Admincp/ListOrders.aspx");
            }
            catch { }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            int userId = 0;
            try
            {
                userId = int.Parse(Session["UserID"].ToString());
                objOrder = orderBL.Select(objOrder);
                objOrder.SystemStatus = EnumStatus.V_ORDER_DELETE;
                objOrder.TransactionOrderStatus = EnumTransactionOrderStatus.V_ORDER_COMPLETED;
                objOrder.LastModifiedId = userId;
                objOrder.LastSaveDate = DateTime.Now;

                orderBL.Update(objOrder);

                CS_OrderHistoryDO objOrderHistory = new CS_OrderHistoryDO();
                objOrderHistory.Action = EnumOrderHistory.V_CHANGE_DELETE;
                objOrderHistory.Contents = EnumOrderHistory.V_CHANGE_DELETE_TEXT;
                objOrderHistory.CreateDate = DateTime.Now;
                objOrderHistory.OrderId = objOrder.Id;
                objOrderHistory.UserId = userId;
                objOrderHistory.Note = txtOrderHistoryNote.Text.Trim();
                objOrderHistory.IP = Request.ServerVariables["REMOTE_ADDR"].Trim();

                new CS_OrderHistoryBL().Insert(objOrderHistory);

                Functions.Alert("Xóa bản ghi thành công", "/Admincp/ListOrders.aspx");
            }
            catch { }

        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            int userId = 0;
            try
            {
                userId = int.Parse(Session["UserID"].ToString());
                objOrder = orderBL.Select(objOrder);
                objOrder.TransactionOrderStatus = ddlOrderStatus.SelectedValue;
                objOrder.LastModifiedId = userId;
                objOrder.LastSaveDate = DateTime.Now;
                objOrder.Note = txtOrderNote.Text;

                orderBL.Update(objOrder);

                CS_OrderHistoryDO objOrderHistory = new CS_OrderHistoryDO();
                objOrderHistory.Action = EnumOrderHistory.V_CHANGE_ORDER;
                objOrderHistory.Contents = EnumOrderHistory.V_CHANGE_ORDER_TEXT;
                objOrderHistory.CreateDate = DateTime.Now;
                objOrderHistory.OrderId = objOrder.Id;
                objOrderHistory.UserId = userId;
                objOrderHistory.Note = txtOrderHistoryNote.Text.Trim();
                objOrderHistory.IP = Request.ServerVariables["REMOTE_ADDR"].Trim();

                if (ddlOrderStatus.SelectedValue.Equals(EnumTransactionOrderStatus.V_ORDER_COMPLETED))
                {
                    objOrderHistory.Action = EnumOrderHistory.V_CHANGE_COMPLETE;
                    objOrderHistory.Contents = EnumOrderHistory.V_CHANGE_COMPLETE_TEXT;
                    if (objOrder.IsUseVirtualAccount)
                    {
                        cmsAccountReceiveMoneyBL accountReceivedMoneyBL = new cmsAccountReceiveMoneyBL();
                        cmsAccountReceiveMoneyDO objAccountReceivedMoney = accountReceivedMoneyBL.SelectByOrder(objOrder.InvoiceNumber);
                        if (objAccountReceivedMoney != null)
                        {
                            if (objAccountReceivedMoney.ID > 0)
                            {
                                objAccountReceivedMoney.Status = EnumReceivedMoneyStatus.V_RECEIVED_OK;
                                objAccountReceivedMoney.UserId = userId;
                                accountReceivedMoneyBL.Update(objAccountReceivedMoney);
                            }
                        }
                    }
                }
                new CS_OrderHistoryBL().Insert(objOrderHistory);

                Functions.Alert("Cập nhật thành công!", "/Admincp/ListOrders.aspx");
            }
            catch { }
        }

        protected void btnCancelOrder_Click(object sender, EventArgs e)
        {
            int userId = 0;
            try
            {
                userId = int.Parse(Session["UserID"].ToString());
                objOrder = orderBL.Select(objOrder);
                objOrder = orderBL.Select(objOrder);
                objOrder.TransactionOrderStatus = EnumTransactionOrderStatus.V_ORDER_CANCEL;
                objOrder.LastModifiedId = userId;
                objOrder.LastSaveDate = DateTime.Now;

                orderBL.Update(objOrder);

                CS_OrderHistoryDO objOrderHistory = new CS_OrderHistoryDO();
                objOrderHistory.Action = EnumOrderHistory.V_CHANGE_CANCEL;
                objOrderHistory.Contents = EnumOrderHistory.V_CHANGE_CANCEL_TEXT;
                objOrderHistory.CreateDate = DateTime.Now;
                objOrderHistory.OrderId = objOrder.Id;
                objOrderHistory.UserId = userId;
                objOrderHistory.Note = "";
                objOrderHistory.IP = Request.ServerVariables["REMOTE_ADDR"].Trim();

                new CS_OrderHistoryBL().Insert(objOrderHistory);

                if (objOrder.IsUseVirtualAccount)
                {
                    cmsAccountReceiveMoneyBL accountReceivedMoneyBL = new cmsAccountReceiveMoneyBL();
                    cmsAccountReceiveMoneyDO objAccountReceivedMoney = accountReceivedMoneyBL.SelectByOrder(objOrder.InvoiceNumber);
                    if (objAccountReceivedMoney != null)
                    {
                        if (objAccountReceivedMoney.ID > 0)
                        {
                            objAccountReceivedMoney.Status = EnumReceivedMoneyStatus.V_RECEIVED_CANCEL;
                            objAccountReceivedMoney.UserId = userId;
                            accountReceivedMoneyBL.Update(objAccountReceivedMoney);
                        }
                    }

                    // Cap nhat lai tai khoan
                    cmsAccountDO objAccount = new cmsAccountDO();
                    cmsAccountBL accountBL = new cmsAccountBL();
                    cmsLogAccountDO objLogAccount = new cmsLogAccountDO();
                    cmsLogAccountBL logAccountBL = new cmsLogAccountBL();
                    accountBL.AccountInfoObject(objOrder.CustomerId);

                    if (objAccount != null)
                    {
                        if (objAccount.AccountId > 0)
                        {
                            objAccount.DepositBeforeTran = objAccount.Deposite;
                            objAccount.Deposite = objAccount.Deposite + objOrder.GrandTotal;
                            objAccount.LastSaveDate = DateTime.Now;
                            objAccount.LastModifiedId = userId;
                            accountBL.Update(objAccount);

                            // Ghi log tai khoan
                            objLogAccount.AccountId = objAccount.AccountId;
                            objLogAccount.Content = "Hoàn tiền vào tài khoản khi hủy đơn hàng: " + objOrder.InvoiceNumber;
                            objLogAccount.CreatedById = userId;
                            objLogAccount.CreatedDate = DateTime.Now;
                            objLogAccount.CurrentDeposite = objAccount.Deposite;
                            objLogAccount.DepositBeforeTran = objAccount.DepositBeforeTran;
                            objLogAccount.FromCustomerId = objOrder.CustomerId;
                            objLogAccount.OrderId = objOrder.Id;
                            objLogAccount.LogAccountPaymentCode = "CANCELORDER";
                            objLogAccount.LogAccountPayment = "Hoàn tiền khi hủy đơn hàng!";
                            objLogAccount.LogAccountType = "INCREASE";
                            logAccountBL.Insert(objLogAccount);
                        }
                    }
                }
                Functions.Alert("Cập nhật thành công!", "/Admincp/ListOrders.aspx");
            }
            catch { }
        }
    }
}
